/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Alert;
import com.riq.entity.Department;
import com.riq.entity.Location;

@SuppressWarnings("serial")
public class MarkupServlet extends HttpServlet {
	
  private static final Logger log = Logger.getLogger(Department.class.getName());
  private static final int MAX_COOKIE_AGE_MS = 60*60*24*1000;  // for cookie age
  private static final Long INIT_LONG = Long.valueOf("999999999"); 
  private Long deptId = INIT_LONG;
  private Long memberId = INIT_LONG;

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    // ---------------------------------------------------------------------------------------------
    //  HEADER
    // ---------------------------------------------------------------------------------------------

    Cookie[] cookie = request.getCookies();
    deptId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvDeptId", "99999"));
    memberId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvMemberId", "99999"));

    String action = request.getParameter("action"); 

    // ---------------------------------------------------------------------------------------------
    //  METHOD DIRECTORY
    // ---------------------------------------------------------------------------------------------

    if ("alertSelect".equalsIgnoreCase(action)) {
      alertSelect(response, request); 
    } else if ("locationSelect".equalsIgnoreCase(action)) {
      locationSelect(response, request); 
    } else if ("locationSet".equalsIgnoreCase(action)) {
      locationSet(response, request); 
    } 

    try
    {
      response.sendRedirect("mainMenu.html");
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }


  //---------------------------------------------------------------------------------------------
  // STEP 1: GET ALERT CHOICES FOR RESPONDER (OR AUTO-SELECT IF THERE'S ONLY ONE ACTIVE)
  // ---------------------------------------------------------------------------------------------

  private void alertSelect(HttpServletResponse response, ServletRequest request) {

    String intent = request.getParameter("intent"); 

    PersistenceManager pm = PMF.get().getPersistenceManager();
    String queryAlert = "select from " + Alert.class.getName() + 
    " where deptId == " + deptId + " && status == 'Active' ";
    List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute();
    log.info("Alerts Qty: " + alerts.size());

    // EMPTY
    if (alerts.isEmpty()) {
      try
      {
        log.info("No Alerts");
        response.sendRedirect("noSuchObject.jsp?errorMessage=NoActiveAlerts");
      } catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
    // ONLY ONE ALERT (AUTO-SELECT, SET COOKIE AND MOVE TO LOCATION SELECT IN STEP 2
    } else if (alerts.size() == 1 && !"terminate".equalsIgnoreCase(intent)) {
    	
        Cookie c = new Cookie("cvAlertId", alerts.get(0).getid().toString());
        c.setMaxAge(MAX_COOKIE_AGE_MS);
        response.addCookie(c);

        if ("markup".equalsIgnoreCase(intent)) {          
          try {
            response.sendRedirect("markup?action=locationSelect" +
            		              "&alertId=" + alerts.get(0).getid().toString() + 
            		              "&deptId=" + deptId.toString() +
            		              "&intent=" + intent);
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        
        
        } else if ("activeLocations".equalsIgnoreCase(intent) ||
        		   "allLocations".equalsIgnoreCase(intent)) {
          try {
            response.sendRedirect("reportingPrep?intent=" + intent +
            		              "&alertId=" + alerts.get(0).getid().toString() +
                                  "&deptId=" + deptId.toString());
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          
    
        } 
        
//        else if ("response".equalsIgnoreCase(intent)) {
//          try {
//            response.sendRedirect("reportingPrep?intent=response" +
//            		              "&alertId=" + alerts.get(0).getid().toString() +
//                                  "&deptId=" + deptId.toString());
//          } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//          }
//        }
                
    // MORE THAN ONE ALERT

    } else {
      request.setAttribute("alerts", alerts);       
      request.setAttribute("intent", intent);
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/alertSelect.jsp");
      try
      {
        dispatcher.forward(request, response);
      } catch (ServletException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }


  // -----------------------------------------------------------------------------------------------
  // STEP 2: SET ALERT COOKIE AND GET LOCATION CHOICES FOR RESPONDER
  // -----------------------------------------------------------------------------------------------

  private void locationSelect(HttpServletResponse response, ServletRequest request) {

    String intent = request.getParameter("intent"); 

    // set alertId cookie for alert selected by responder
    String alertId = (String) request.getParameter("alertId");
    Cookie c = new Cookie("cvAlertId", alertId);
    c.setMaxAge(MAX_COOKIE_AGE_MS);
    response.addCookie(c);
    
    PersistenceManager pm = PMF.get().getPersistenceManager();

    // get locations for this department for responder to choose from
    String queryLocations = "select from " + Location.class.getName() + 
    " where deptId == " + deptId + " && special == 'yes' order by sequence";
    List<Location> locations = (List<Location>) pm.newQuery(queryLocations).execute();  
    request.setAttribute("locations", locations);
    request.setAttribute("intent", intent);

    // check to see if there's at least one location
    if (locations.isEmpty()) {
      try
      {
        response.sendRedirect("noSuchObject.jsp?nullObjectType=special-locations");
        log.info("No Special Locations");
      } catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } 
    }

    // pass the alert message for display on Location Select page
    Alert a = pm.getObjectById(Alert.class, Long.valueOf(alertId));
    request.setAttribute("alert", a);

    RequestDispatcher dispatcher = 
      getServletContext().getRequestDispatcher("/locationSelect.jsp");
    try
    {
      dispatcher.forward(request, response);
    } catch (ServletException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }


  // -----------------------------------------------------------------------------------------------
  //STEP 3: SET LOCATION COOKIE, CREATE TRACKING RECORD AND SHOW UPDATED REPORT
  // -----------------------------------------------------------------------------------------------

  private void locationSet(HttpServletResponse response, ServletRequest request) {

    // set locationId cookie for location selected by responder
    String locationId = request.getParameter("locationId");
    
    Cookie c = new Cookie("cvLocId", locationId);
    c.setMaxAge(MAX_COOKIE_AGE_MS);
    response.addCookie(c);  
    try
    {
      response.sendRedirect("tracking?action=create&intent=markup");
    } catch (IOException e)
    {
      // TODO
      e.printStackTrace();
    }

  }

}




